<?php


namespace app\api\controller\uniapp;


use app\api\model\Users;
use app\api\model\UserStore;
use app\common\controller\Api;
use app\api\controller\Wxutils;

/**
 * 小程序首页接口
 * Class Index
 * @package app\api\controller\uniapp
 */
class User extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    private $loginVo = ['user_id','mobile','password','token'];

    public function index(){

    }

    /**
     * 微信小程序登陆
     * @param $code
     */
    public function login(){
        $code = $this->request->param('code');
        $uid = $this->request->param('uid');
        //获取用户openid
        $wxuser = Wxutils::get_openid($code);
        if (isset($uid) && !empty($uid)){
            $wxuser['first_leader'] = $uid;
        }

        if(isset($wxuser['unionid'])){
            $user = Users::where('unionid',$wxuser['unionid'])->find();
            if($user){
                if(empty($user['app_openid'])){
                    $user['app_openid'] = $wxuser['openid'];
                    $user->save();
                }
            }else{
                //注册新用户
                $user = $this->routine_reg($wxuser);
            }
        }
        if(isset($wxuser['openid'])){
            $user = Users::where('app_openid',$wxuser['openid'])->find();
            if(!$user){
                //注册新用户
                $user = $this->routine_reg($wxuser);
            }
        }
        session('authuser',$user->toArray());
        if(isset($user['token']) && !empty($user['token'])){
            $this->success('登陆成功',$user['token']);
        } else{
            $this->error('登陆失败');
        }
    }

    /**
     * 手机app登陆
     */
    public function applogin(){
        $phone = $this->request->post('phone');
        $password = $this->request->post('password');
        $user = Users::where('mobile',$phone)->find();
        if(!$user){
            $this->error("用户不存在");
        }
        if(encrypt($password) != $user['password']){
            return $this->error("密码错误");
        }
        $user->visible($this->loginVo);
        $user['password'] = $password;
        $this->success('登陆成功',$user);
    }

    /**
     * 微信小程序注册
     * @param $wxuser
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    private function routine_reg($wxuser){
        //账户不存在 注册一个
        $wxuser['app_openid'] = $wxuser['openid'];
        unset($wxuser['openid']);
        //$map['nickname'] = filterEmoji($data['nickname']);//进行emoji过虑~~
        $wxuser['reg_time'] = time();
        $wxuser['bind_time'] = time();
        $wxuser['token'] = md5(time() . mt_rand(1, 999999999));
        //$map['oauth'] = $data['oauth'];
        //$map['head_pic'] = !empty($data['head_pic']) ? $data['head_pic'] : '/public/images/icon_goods_thumb_empty_300.png';
        //$map['sex'] = $data['sex'] === null ? 0 :  $data['sex'];
        //$map['first_leader'] = cookie('first_leader'); // 推荐人id
        // 成为分销商条件
//        $distribut_condition = tpCache('distribut.condition');
//        if($distribut_condition == 0){    // 直接成为分销商, 每个人都可以做分销
//            $map['is_distribut']  = 1;
//        }

        $wxuser['password']=encrypt(config('default_pass'));

        $add = Users::create($wxuser,true);
        $user = Users::get($add->id);
        return $user;
    }

    /**
     * 生成带参数的小程序码
     * @param string $scene 场景值参数，最大32个字符
     * @param string $page 小程序页面路径，根目录开始
     * @param int $width 二维码宽度
     * @return string 图片保存路径
     * @throws Exception
     */
    public function createQrcode($tjuid, $width = 430)
    {
        $page = 'pages/index/index?uid='.$tjuid;
        try {
            $accessToken = Wxutils::get_access_token();

            // 接口B：生成无限量带参数小程序码
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";

            // 请求参数
            $params = [
                'scene'      => "带参数二维码",
                'page'       => $page,
                'width'      => $width,
                'auto_color' => false,
                'line_color' => ['r' => 0, 'g' => 0, 'b' => 0],
                'is_hyaline' => false
            ];

            // 发送POST请求
            $imageData = http_curl($url,"POST",$params,"application/json");

            // 检查返回是否为错误信息(json格式)
            $jsonCheck = json_decode($imageData, true);
            if (isset($jsonCheck['errcode']) && $jsonCheck['errcode'] != 0) {
                throw new Exception('生成小程序码失败: ' . $jsonCheck['errmsg']);
            }
            // 保存图片到本地
            $savePath = $this->saveImage($imageData);

            return $savePath;
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * 保存图片到服务器
     * @param string $imageData 图片二进制数据
     * @return string 图片保存路径
     */
    private function saveImage($imageData)
    {
        // 创建保存目录
        $uploadDir = app()->getRootPath() . 'public' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'qrcode' . DIRECTORY_SEPARATOR;
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        // 生成唯一文件名
        $fileName = date('YmdHis') . '_' . uniqid() . '.png';
        $savePath = $uploadDir . $fileName;

        // 写入文件
        file_put_contents($savePath, $imageData);

        // 返回可访问的URL路径
        return '/uploads/qrcode/' . $fileName;
    }

    public function saveuser(){
        $user = session('authuser');
        //获取参数
        $params = $this->request->param();
        //修改密码
        if($params['name']=='password'){
            //检查旧密码
            if(encrypt($params['old_pass'])!=$user['password']){
                $this->error("原密码错误");
            }
            $params['value'] = encrypt($params['value']);
        }
        //修改支付密码
        if($params['name']=='paypwd'){
            //检查旧密码
            if(encrypt($params['old_pass'])!=$user['paypwd']){
                $this->error("原密码错误");
            }
            $params['value'] = encrypt($params['value']);
        }
        //修改用户
        $upok = Users::where('user_id',$user['user_id'])->update([$params['name']=>$params['value']]);
        if($upok){
            $this->success("设置成功");
        }else{
            $this->error("设置失败");
        }
    }

    public function userqrcode(){
        $user = session('authuser');

        //加载带参数二维码
        $code = Wxutils::getWxACodeUnlimitUser("/pages/mine/userpay/userpay",$user['user_id']);
        if($code==null){
            $this->error("获取二维码失败",$user);
        }
        $user['user_qrcode'] = config('img_url').$code;
        $this->success("加载成功",$user);
    }

    public function saveunionid(){
        $users = Users::where('isun',0)->select();
        foreach ($users as $k=>$v){
            if(empty($v['unionid'])){
                $unionid = Wxutils::get_gzh_unionid($v['openid']);
                $v->unionid = isset($unionid['unionid'])?$unionid['unionid']:'';
            }
            $v->isun = 1;
            $v->save();
        }

//        $users = Users::where('user_id',9)->find();
//        if(empty($users['unionid'])){
//            $unionid = Wxutils::get_gzh_unionid($users['openid']);
//            $users->unionid = isset($unionid['unionid'])?$unionid['unionid']:'';
//        }
//        $users->isun = 1;
//        halt($users->toArray());
//        $users->save();

    }

    //验证token
    public function checktoken(){
        $userToken = $this->request->param('usertoken');
        $user = Users::where('token',$userToken)->find();
        if($user){
            $this->success('验证成功');
            session('authuser',$user->toArray());
        }else{
            $this->error('验证失败');
        }
    }

    public function getuserinfo(){
        $user = session('authuser');
        $userinfo = Wxutils::getuserinfo();
        halt($userinfo);
    }
}